package com.swordliu.messagequeue.rabbit;

import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;

/**
 * Created by SwordLiu on 2017-06-29.
 */
public class SpringRabbitMQ {

    public final static String QUEUE_NAME = "hello";

    public void send() throws Exception{

        //spring amqp 官网 demo
        ConnectionFactory factory = new CachingConnectionFactory();

        // set up the queue, exchange, binding on the broker
        //设置队列、交换机、绑定
        RabbitAdmin admin = new RabbitAdmin(factory);
        Queue queue = new Queue("myQueue");
        admin.declareQueue(queue);
        TopicExchange topicExchange = new TopicExchange("myExchange");
        admin.declareExchange(topicExchange);
        admin.declareBinding(BindingBuilder.bind(queue).to(topicExchange).with("foo.*"));

        // set up the listener and container
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(factory);
        Object listener = new Object(){
            public void handleMessage(String foo) {
                System.out.println(foo);
            }
        };
        MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
        container.setMessageListener(adapter);
        container.setQueueNames("myQueue");
        container.start();

        // send something
        RabbitTemplate template = new RabbitTemplate(factory);
        template.convertAndSend("myExchange", "foo.bar", "hello world!");
        Thread.sleep(1000);
        container.stop();

    }

    public static void main(String[] args) throws Exception{
        SpringRabbitMQ springRabbitMQ = new SpringRabbitMQ();

        springRabbitMQ.send();
    }

}
